package uk.co.nazz.f21mc_a2.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import uk.co.nazz.f21mc_a2.DiaryApplication;
import uk.co.nazz.f21mc_a2.R;
import uk.co.nazz.f21mc_a2.diary.Attendee;
import uk.co.nazz.f21mc_a2.utils.AttendeesAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Events;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewEventActivity extends Activity implements OnClickListener {

	private Button editButton;
	private Button deleteButton;
	private String eventId;
	private String title;
	private Calendar start;
	private Calendar end;
	private String location;
	private String description;
	private String recurrence;

	private TextView titleView;
	private TextView locationView;
	private TextView descriptionView;
	private TextView recurrenceView;
	private TextView startView;
	private TextView endView;
	private ListView attendeesListView;
	private ArrayList<Attendee> attendees;
	private AttendeesAdapter adapter;
	private DiaryApplication diaryApplication;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			eventId = extras.getString("eventId");
		} else {
			Log.v("F21MC_2", "No eventId passed to ViewEventActivity");
			finish();
		}

		diaryApplication = (DiaryApplication) this.getApplication();

		setContentView(R.layout.viewevent);

		editButton = (Button) findViewById(R.id.viewevent_edit_button);
		editButton.setOnClickListener(this);

		deleteButton = (Button) findViewById(R.id.viewevent_delete_button);
		deleteButton.setOnClickListener(this);

		// find the form fields
		titleView = (TextView) findViewById(R.id.viewevent_event_title);
		locationView = (TextView) findViewById(R.id.viewevent_event_location);
		descriptionView = (TextView) findViewById(R.id.viewevent_description);
		recurrenceView = (TextView) findViewById(R.id.viewevent_recurrence);
		startView = (TextView) findViewById(R.id.viewevent_start);
		endView = (TextView) findViewById(R.id.viewevent_end);
		attendeesListView = (ListView) findViewById(R.id.viewevent_listview_attendees);

		// allow the attendees list view to be scrolled while the
		// whole activity is also contained in a ScrollView
		attendeesListView.setOnTouchListener(new ListView.OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent event) {
				int action = event.getAction();
				switch (action) {
				case MotionEvent.ACTION_DOWN:
					// Disallow ScrollView to intercept touch
					// events.
					view.getParent().requestDisallowInterceptTouchEvent(true);
					break;

				case MotionEvent.ACTION_UP:
					// Allow ScrollView to intercept touch events.
					view.getParent().requestDisallowInterceptTouchEvent(false);
					break;
				}

				view.onTouchEvent(event);
				return true;
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();

		// set form fields

		// query the data for the event
		String[] projection = { Events.TITLE, Events.DTSTART, Events.DTEND,
				Events.DESCRIPTION, Events.EVENT_LOCATION, Events.RRULE };
		String selection = Events._ID + "=?";
		String[] seletionArgs = { eventId };

		Cursor cursor = getContentResolver().query(Events.CONTENT_URI,
				projection, selection, seletionArgs, null);
		if (cursor.moveToFirst()) {

			title = cursor.getString(cursor.getColumnIndex(Events.TITLE));
			location = cursor.getString(cursor
					.getColumnIndex(Events.EVENT_LOCATION));
			recurrence = cursor.getString(cursor.getColumnIndex(Events.RRULE));
			description = cursor.getString(cursor
					.getColumnIndex(Events.DESCRIPTION));

			start = Calendar.getInstance();
			start.setTimeInMillis(Long.parseLong(cursor.getString(cursor
					.getColumnIndex(Events.DTSTART))));
			end = Calendar.getInstance();
			end.setTimeInMillis(Long.parseLong(cursor.getString(cursor
					.getColumnIndex(Events.DTEND))));

			// create the adapter for the attendees list view

			attendees = new ArrayList<Attendee>();
			adapter = new AttendeesAdapter(this,
					android.R.layout.simple_list_item_1, attendees);

			addAttendees();

			attendeesListView.setAdapter(adapter);

			titleView.setText(title);
			locationView.setText(location);
			descriptionView.setText(description);
			recurrenceView.setText(formatRecurrenceString(recurrence));
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.UK);
			startView.setText(sdf.format(start.getTime()));
			endView.setText(sdf.format(end.getTime()));

			// set the title of the activity to be the title of the event
			String t = "";
			if (title.length() > 10) {
				t = title.substring(0, 10);
			} else {
				t = title;
			}

			setTitle("EVENT: " + t);

		}

	}

	private void addAttendees() {

		// clear the ArrayList of attendees
		// for when the page is being populated
		// in the onResume method
		// query for the attendees
		attendees.clear();
		String[] attendeeProjection = { Attendees.ATTENDEE_NAME };
		String attendeeSelection = Attendees.EVENT_ID + "=?";
		String[] attendeeseletionArgs = { eventId };

		Cursor attendeeCursor = getContentResolver().query(
				Attendees.CONTENT_URI, attendeeProjection, attendeeSelection,
				attendeeseletionArgs, null);
		int i = 1;
		while (attendeeCursor.moveToNext()) {
			String name = attendeeCursor.getString(attendeeCursor
					.getColumnIndex(Attendees.ATTENDEE_NAME));
			if (name != null) {
				attendees.add(new Attendee(i, name, ""));
				adapter.notifyDataSetChanged();
				i++;
			}
		}

	}

	private String formatRecurrenceString(String rrule) {
		String returnString = "";
		if (rrule != null) {
			if (rrule.length() > 0) {
				String[] rule = rrule.split("=|;");

				if (rule.length == 4) {
					returnString = "Occurs " + rule[1] + " for " + rule[3]
							+ " occurrences";
				} else {
					returnString = "Occurs " + rule[1];
				}
			}
		}
		return returnString;
	}

	// handle the onClick events
	@Override
	public void onClick(View view) {
		if ((Button) view == editButton) {
			// edit selected, start new EventEditor activity
			Intent intent = new Intent(this, EventEditor.class);
			intent.putExtra("eventId", eventId);
			startActivity(intent);
		} else if ((Button) view == deleteButton) {

			// delete button selected
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				@Override
				// confirm deletion with user
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						if (diaryApplication.getDiary().deleteEvent(eventId)) {
							Toast toast = Toast.makeText(
									getApplicationContext(), "Event " + title
											+ " deleted", Toast.LENGTH_SHORT);
							toast.show();
						} else {
							Toast toast = Toast.makeText(
									getApplicationContext(),
									"Error deleting event " + title,
									Toast.LENGTH_SHORT);
							toast.show();
						}

						finish();
						break;

					case DialogInterface.BUTTON_NEGATIVE:
						break;
					}
				}
			};

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure you want to delete this event?")
					.setPositiveButton("Yes", dialogClickListener)
					.setNegativeButton("No", dialogClickListener).show();
		}

	}

}
